package tech.heptagram.staff.cas.controller.view;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import tech.heptagram.core.common.rest.ResponseResult;
import tech.heptagram.core.common.rest.RestResultEnum;
import tech.heptagram.staff.cas.common.AssertUtils;
import tech.heptagram.staff.cas.common.CurrentUserUtil;
import tech.heptagram.staff.cas.domain.info.RolePermissionReq;
import tech.heptagram.staff.cas.domain.po.DataAuth;
import tech.heptagram.staff.cas.service.staff.CasDataAuthService;
import tech.heptagram.staff.cas.service.staff.CasRoleService;

/**
 * @author wang.yuchuan
 * @createdAt 2019/1/11
 */
@RestController
@RequestMapping("/api/view/sys/dataauth")
public class CasDataAuthApiController {

    @Resource
    private CasDataAuthService casDataAuthService;

    @Resource
    private CasRoleService casRoleService;

    @GetMapping("/list/all")
    public ResponseResult<List<DataAuth>> findAll() {
        try {
            List<DataAuth> allDataAuths = casDataAuthService.findAll();
            return new ResponseResult<>(allDataAuths);
        } catch (Exception ex) {
            ResponseResult responseResult = new ResponseResult();
            responseResult.setMsg(ex.getMessage());
            responseResult.setRetcode(RestResultEnum.ERROR.getKey());
            return responseResult;
        }
    }

    @PostMapping("/save")
    public ResponseResult<Boolean> save(@RequestBody DataAuth dataAuth) {
        AssertUtils.notNull(dataAuth, "要保存的数据权限为Null");
        dataAuth.setModifiedBy(CurrentUserUtil.getCurrentUser().getTrueName());
        if (Objects.nonNull(dataAuth.getId())) {
            casDataAuthService.update(dataAuth);
        } else {
            dataAuth.setCreatedBy(CurrentUserUtil.getCurrentUser().getTrueName());
            casDataAuthService.save(dataAuth);
        }
        return new ResponseResult<>(true);
    }

    @PostMapping("/save/permission")
    public ResponseResult saveRoleDataAuth(@RequestBody RolePermissionReq req) {
        req.setCreatedBy(CurrentUserUtil.getCurrentUser().getTrueName());

        casRoleService.saveRoleDataAuth(req);
        return new ResponseResult();
    }

    @GetMapping("/roleId/{roleId}")
    public ResponseResult<Integer> findByRoleId(@PathVariable Integer roleId) {
        DataAuth dataAuth = casDataAuthService.findByRoleId(roleId);
        if (Objects.nonNull(dataAuth)) {
            return new ResponseResult<>(dataAuth.getId());
        }
        return new ResponseResult<>(0);
    }
}
